package com.email.impl;

import com.email.IEmailParser;
import com.email.utils.StringUtil;
import com.pff.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * eml 文件解析
 * 
 * @author wanghong
 * 
 */
public class PSTParser implements IEmailParser {

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public void parse(String path, String name, String rootPath) throws Exception {
		/*if (name.toLowerCase().indexOf(".pst") <= 0) {
			throw new Exception("pst文件类型不匹配" + name);
		}*/
		try {
		PSTFile pstFile = new PSTFile(path+"\\"+name);
		this.processFolder(pstFile.getRootFolder(),name,rootPath);
		} catch (final Exception err) {
			err.printStackTrace();
		}
	}

	public void processFolder(final PSTFolder folder, final String filename, String rootPath) throws PSTException, IOException {
		// go through the folders...
		if (folder.hasSubfolders()) {
			final Vector<PSTFolder> childFolders = folder.getSubFolders();
			for (final PSTFolder childFolder : childFolders) {
				this.processFolder(childFolder,filename, rootPath);
			}
		}
		// and now the emails for this folder
		if (folder.getContentCount() > 0) {
			PSTMessage email = (PSTMessage) folder.getNextChild();
			List<Map<String,Object>> listMain = new ArrayList<Map<String, Object>>();
			while (email != null) {
				Map<String,Object> mapMain = setMapMain(email,filename,rootPath);
				listMain.add(mapMain);
				email = (PSTMessage) folder.getNextChild();
			}
		}
	}

	private Map<String,Object> setMapMain(PSTMessage email, String filename, String rootPath) throws PSTException, IOException {
		String mainUuid = UUID.randomUUID().toString();
		Map<String, Object> returnmap = new HashMap<String, Object>();
		returnmap.put("id", mainUuid);										//id
		returnmap.put("filename", filename);								//文件名
		returnmap.put("subject", email.getSubject());						//主题

		returnmap.put("filefullcontent", email.getBodyHTML());				//原始内容(包含html格式)，用于展示
		returnmap.put("filecontent", email.getBody());               		//纯文本内容

		returnmap.put("from", email.getSenderEmailAddress());				//发件人邮箱地址
		returnmap.put("fromname", email.getSenderName());					//发件人姓名
		returnmap.put("sendtime",sdf.format(email.getClientSubmitTime()));  //发送时间

		returnmap.put("to", email.getDisplayTo());              			//收件人邮箱地址数组
		returnmap.put("toname", email.getReceivedByName());     			//收件人姓名数组
		returnmap.put("ccname", email.getDisplayCC());     					//抄送人姓名数组
		returnmap.put("bccname", email.getDisplayBCC());     			    //密送人姓名数组

		//转移附件
		if (email.getNumberOfAttachments() > 0){
				for (int i =0;i<email.getNumberOfAttachments();i++){
					PSTAttachment attach = email.getAttachment(i);
					String dirurl = rootPath + "\\attachment\\" + mainUuid;
					File dir = new File(dirurl);
					if (!dir.exists()) {
						dir.mkdirs();
					}
					String fn = attach.getLongFilename();
					if (StringUtil.isEmpty(fn)) {
						fn = attach.getFilename();
					}
					String rep = "[`/\\*?<>|\t\n]";
					Pattern p_space = Pattern.compile(rep, Pattern.CASE_INSENSITIVE);
					Matcher m_space = p_space.matcher(fn);
					fn = m_space.replaceAll("");
					String url = dirurl + "\\" + fn;
					InputStream attachmentStream = attach.getFileInputStream();
					FileOutputStream out = new FileOutputStream(new File(url));
					// 8176 is the block size used internally and should give the best performance
					int bufferSize = 8176;
					byte[] buffer = new byte[bufferSize];
					int count = attachmentStream.read(buffer);
					while (count == bufferSize) {
						out.write(buffer);
						count = attachmentStream.read(buffer);
					}
					byte[] endBuffer = new byte[count];
					System.arraycopy(buffer, 0, endBuffer, 0, count);
					out.write(endBuffer);
					out.close();
					attachmentStream.close();
				}
			}

		return returnmap;
	}
	public static void main(String[] args) {
		PSTParser a = new PSTParser();
		try {
			a.parse("F:\\MyDownloads", "kevin12138az@163.com.pst", "F:");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
